package inits

import (
	"fmt"
	mqtt "github.com/eclipse/paho.mqtt.golang"
	"github.com/zeromicro/go-zero/core/logx"
	"smart-health-platforms/config"
	"time"
)

// mqtt连接
func InitMqtt() {
	config.Opts = mqtt.NewClientOptions()
	mqttConf := config.AppCong.Mqtt
	config.Opts.AddBroker(fmt.Sprintf("tcp://%s:%v",
		mqttConf.Host,
		mqttConf.Port))
	config.Opts.SetCleanSession(true)
	config.Opts.SetAutoReconnect(true)
	config.Opts.SetMaxReconnectInterval(5 * time.Second)
}

// 初始化MQTT客户端配置
func Configuration() {
	config.Opts = mqtt.NewClientOptions()
	config.Opts.AddBroker(fmt.Sprintf("tcp://%s:%d", config.AppCong.Mqtt.Host, config.AppCong.Mqtt.Port)) // 设置MQTT代理地址
	config.Opts.SetClientID(config.AppCong.Mqtt.SetClientId)                                              // 设置客户端ID
}

// 成功消息回调
func SuccessMessageCallback(messageHandler func(client mqtt.Client, msg mqtt.Message)) {
	config.Opts.OnConnect = func(client mqtt.Client) {
		logx.Info("已连接到EMQX服务器")
		// 订阅体温主题
		if token := client.Subscribe("sensors/temperature", 1, messageHandler); token.Wait() && token.Error() != nil {
			logx.Errorf("订阅主题失败: %v", token.Error())
		} else {
			logx.Info("已订阅主题: sensors/temperature")
		}
	} // 设置客户端ID
}

// 创建MQTT客户端并连接
func ClientCallback() mqtt.Client {
	client := mqtt.NewClient(config.Opts)
	if token := client.Connect(); token.Wait() && token.Error() != nil {
		logx.Errorf("连接EMQX失败: %v", nil)
	}
	return client
}
